package com.hbnu.thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author kittychen
 * @since 2025-10-23 19:26
 */
public class Ticket implements Runnable {
    private final Lock lock = new ReentrantLock();  // 创建一个锁对象
    private int ticket = 30;
    @Override
    public /* synchronized */ void run(){
        while (true) {
            lock.lock();  // 加锁
            if (ticket > 0) {
                System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket + "号票");
                ticket--;
            } else {
                break;
            }
            lock.unlock();  // 解锁

            // synchronized (this) {
            //     if (ticket > 0) {
            //         System.out.println(Thread.currentThread().getName() + "正在卖第" + ticket + "号票");
            //         ticket--;
            //     } else {
            //         break;
            //     }
            // }
        }
    }
}
